package cc.rengu.igas.bsps.common.util;

import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.List;

public class CSVFileUtil {

    /**
     * 生成CSV文件
     *
     * @param path     路径
     * @param dataList 数据
     * @return 结果
     */
    public static boolean exportCSV(String path, List<String> dataList) {
        boolean result = false;
        RgLogger rglog = RgLog.getLogger(CSVFileUtil.class.getName());
        if (CollectionUtils.isEmpty(dataList)) {
            //无数据，返回false
            rglog.debug("无数据，不生成CSV文件");
            return false;
        }

        FileOutputStream out = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            File file = new File(path);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }

            out = new FileOutputStream(file);
            osw = new OutputStreamWriter(out, "UTF-8");
            //BOM标签 防止Excel打开 UTF-8乱码
            osw.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
            bw = new BufferedWriter(osw);
            for (String line : dataList) {
                bw.append(line);
                bw.newLine();
            }
            result = true;
        } catch (Exception e) {
            rglog.error(e.getMessage());
            rglog.error("生成CSV文件失败！path:{}", path);
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    rglog.error("关闭BufferedWriter失败");
                    rglog.error(e.getMessage());
                }
            }

            if (null != osw) {
                try {
                    osw.close();
                } catch (IOException e) {
                    rglog.error("关闭OutputStreamWriter失败");
                    rglog.error(e.getMessage());
                }
            }

            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    rglog.error("关闭FileOutputStream失败");
                    rglog.error(e.getMessage());
                }
            }
        }
        return result;
    }
}
